<template>
  <div v-loading="loading">
    <el-form ref="form" :model="form" :rules="rules" label-width="120px" class="dataForm">
      <div class="area-header">
        <span class="area-header-title">{{ $t('管理费计提规则') }}</span>
      </div>
      <el-table :data="form.fundManagementPhaseList" border>
        <el-table-column :label="$t('阶段')" align="center" prop="phase" :formatter="fundPhaseFormat" />
        <el-table-column :label="$t('计提基数')" align="center" prop="accrualBase" :formatter="accrualBaseFormat" />
        <!--        <el-table-column :label="$t('管理费比例(%)')" align="center" prop="managementFeeRatio" />-->
        <el-table-column :label="$t('起始日期')" align="center" prop="startDate">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.startDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('结束日期')" align="center" prop="endDate">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.endDate) }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('计提月数')" align="center" prop="months" />
        <el-table-column :label="$t('计提天数')" align="center" prop="days" />
        <el-table-column :label="$t('费率')" align="center" prop="managementRate">
          <template slot-scope="scope">
            <el-link type="primary" class="link_a" @click="setManagementRate(scope.row)">
              <span v-if="scope.row.whetherFixed === 'Y'">{{ scope.row.managementRate }}</span>
              <span v-else-if="scope.row.whetherFixed === 'N'">{{ '自定义' }}</span>
              <span v-else>{{ '设置' }}</span>
            </el-link>
          </template>
        </el-table-column>
      </el-table>
      <el-row>
        <el-col :span="12">
          <el-form-item :label="$t('年度')" prop="year">
            <!--            <DatePicker-->
            <!--              v-model="form.year"-->
            <!--              type="year"-->
            <!--              value-format="yyyy"-->
            <!--              :placeholder="$t('年度')"-->
            <!--              @change="changeHandle"-->
            <!--            />-->
            <DatePicker
              v-model="form.year"
              type="year"
              value-format="yyyy"
              :placeholder="$t('年度')"
              @change="setStartEndDate"
            />

          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('计提周期')" prop="accrualPeriod">
            <el-select v-model="form.accrualPeriod" :placeholder="$t('计提周期')" @change="setStartEndDate">
              <!--              <el-select v-model="form.accrualPeriod" :placeholder="$t('计提周期')" @change="changeHandle">-->
              <el-option
                v-for="dict in accrualPeriodOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('计提开始日期')" prop="provisionStartDate">
            <DatePicker
              v-model="form.provisionStartDate"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('计提开始日期')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('计提结束日期')" prop="provisionEndDate">
            <DatePicker
              v-model="form.provisionEndDate"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('计提结束日期')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('天数计算方式')" prop="dayCalMode">
            <el-select v-model="form.dayCalMode" :placeholder="$t('天数计算方式')" @change="changeCalMode">
              <el-option
                v-for="dict in dayCalModeOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <!--        <el-col :span="12">
          <el-form-item :label="$t('实缴金额') + $t('金额单位')" prop="beginningPaidInAmount">
            <Money v-model="form.beginningPaidInAmount" :placeholder="$t('实缴金额')" unit="w">
              &lt;!&ndash;              <el-button slot="append" @click="beginningPaidInAmountHandle">{{ $t('查看') }}</el-button>&ndash;&gt;
            </Money>
          </el-form-item>
        </el-col>-->
        <el-col :span="12">
          <el-form-item :label="$t('类型')" prop="type">
            <el-select v-model="form.type" :placeholder="$t('类型')">
              <el-option
                v-for="dict in typeOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('计提参照日')" prop="accrualConsultDate">
            <el-select v-model="form.accrualConsultDate" :placeholder="$t('计提参照日')" @change="getFoundationDate(form.accrualConsultDate)">
              <el-option
                v-for="dict in accrualConsultDateOptions"
                :key="dict.dictValue"
                :label="$t(dict.dictLabel)"
                :value="dict.dictValue"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('基金成立日')" prop="foundationDate">
            <DatePicker
              v-model="form.foundationDate"
              :disabled="foundationDateDisable"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('基金成立日')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('天数')" prop="yearDays">
            <span slot="label">
              {{ $t('天数') }}
              <el-tooltip :content="$t('协议中规定的年/季度计提天数')" placement="top">
                <i class="el-icon-question" />
              </el-tooltip>
            </span>
            <el-input v-model="form.yearDays" :placeholder="$t('天数')" show-word-limit />
          </el-form-item>
        </el-col>
        <!-- <el-col :span="12">
          <el-form-item :label="$t('认缴金额') + $t('金额单位')" prop="subscribedAmount">
            <Money v-model="form.subscribedAmount" :placeholder="$t('认缴金额')" unit="w" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('在投金额') + $t('金额单位')" prop="beginningReinvestedAmount">
            <Money v-model="form.beginningReinvestedAmount" :placeholder="$t('在投金额')" unit="w" />
          </el-form-item>
        </el-col>-->
        <el-col :span="12">
          <el-form-item :label="$t('收取日期')" prop="collectionDate">
            <DatePicker
              v-model="form.collectionDate"
              type="date"
              value-format="yyyy-MM-dd"
              :placeholder="$t('收取日期')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('管理费金额') + $t('金额单位')" prop="receivableManagementFee">
            <Money v-model="form.receivableManagementFee" :placeholder="$t('管理费金额')" unit="w" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="$t('管理费计提说明')" prop="remark">
            <el-input v-model="form.remark" type="textarea" :maxlength="2000" show-word-limit :placeholder="$t('管理费计提说明')" />
          </el-form-item>
        </el-col>
      </el-row>

      <!--管理费明细-->
      <div class="list-table" style="padding: 0; box-shadow: rgba(218, 223, 232, 0) 0 3px 12px 2px;">
        <div class="area-header">
          <span class="area-header-title">{{ $t('管理费明细') }}</span>
        </div>
        <el-table v-loading="excelLoading" :data="form.fundManageFeeDetailList" border class="nowrapTable formTable">
          <el-table-column :label="$t('出资人名称')" align="center" prop="userName" min-width="180" show-overflow-tooltip />
          <el-table-column :label="$t('合伙人类型')" align="center" prop="partnerType" min-width="140" show-overflow-tooltip />
          <el-table-column :label="$t('计算基数-实缴金额') + $t('金额单位')" align="center" min-width="180" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-form-item :prop="'fundManageFeeDetailList.' + scope.$index + '.beginningPaidInAmount'">
                <Money v-model="scope.row.beginningPaidInAmount" :placeholder="$t('计算基数-实缴金额')" unit="w" @change="calSjAmount" @paste.native="copyPaste($event,scope,'beginningPaidInAmount')" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('计算基数-认缴金额') + $t('金额单位')" align="center" min-width="180" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-form-item :prop="'fundManageFeeDetailList.' + scope.$index + '.subscribedAmount'">
                <Money v-model="scope.row.subscribedAmount" :placeholder="$t('计算基数-认缴金额')" unit="w" @change="calRjAmount" @paste.native="copyPaste($event,scope,'subscribedAmount')" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('计算基数-在投金额') + $t('金额单位')" align="center" min-width="180" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-form-item :prop="'fundManageFeeDetailList.' + scope.$index + '.beginningReinvestedAmount'">
                <Money v-model="scope.row.beginningReinvestedAmount" :placeholder="$t('计算基数-在投金额')" unit="w" @change="calZtAmount" @paste.native="copyPaste($event,scope,'beginningReinvestedAmount')" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('管理费金额') + $t('金额单位')" align="center" min-width="180" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-form-item :prop="'fundManageFeeDetailList.' + scope.$index + '.managementFee'">
                <Money v-model="scope.row.managementFee" :placeholder="$t('管理费金额')" unit="w" @change="calManagementFee" @paste.native="copyPaste($event,scope,'managementFee')" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column :label="$t('操作')" fixed="right" align="center" class-name="small-padding fixed-width" width="80">
            <template slot-scope="scope">
              <el-button
                v-hasPermi="['fund:managementfee:remove']"
                size="small"
                type="text"
                icon="el-icon-delete"
                @click="delRowDeal(scope.$index,scope.row)"
              >{{ $t('删除') }}</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="tol">
          <el-button type="primary" icon="el-icon-download" size="mini" @click.native="downloadCalResult(managerExcelFileId)">{{ $t('下载模板') }}</el-button>
          <el-upload
            ref="upload"
            :limit="1"
            accept=".xlsx, .xls"
            :headers="upload.headers"
            :action="upload.url"
            :disabled="upload.isUploading"
            :before-upload="handleBeforeUploadExcel"
            :on-success="handleFileSuccessExcel"
            :on-exceed="handleFileExceedExcel"
            :data="templateForm"
            class="uploadExcel"
          >
            <el-button type="primary" icon="el-icon-upload" size="mini">{{ $t('更新模板') }}</el-button>
          </el-upload>
          <el-button type="primary" style="margin-left: 15px;margin-right: 5px" icon="el-icon-check" size="mini" @click="templateExcelHandle()">{{ $t('计算') }}</el-button>
          <el-button v-if="form.excelFileId" type="primary" icon="el-icon-download" size="mini" @click="downloadCalResult(form.excelFileId)">{{ $t('下载计算过程') }}</el-button>
        </div>
      </div>

    </el-form>
    <div slot="footer" class="dialog-footer" style="text-align: right;">
      <!--保存，保存并启动流程，取消 三个按钮-->
      <save-btn has-permi="fund:managementfee" cache-key="fund_manager_fee" :bus-data="form" />
    </div>

    <el-dialog :title="$t('期初实缴金额出资人信息')" :visible.sync="lpInfoOpen" :close-on-click-modal="false" :lock-scroll="false" append-to-body>
      <el-table v-loading="lpInfoLoading" :data="beginningPaidInAmountLpInfoList" border>
        <el-table-column :label="$t('出资人名称')" align="center" prop="lpName" show-overflow-tooltip />
        <el-table-column :label="$t('认缴金额') + $t('金额单位')" align="center" prop="subscribedAmount">
          <template slot-scope="scope">
            <span>{{ moneyFormat(scope.row.subscribedAmount, 'w') }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('认缴比例(%)')" align="center" prop="subscribedRatio" />
        <el-table-column :label="$t('期初实缴金额') + $t('金额单位')" align="center" prop="beginningPaidInAmount">
          <template slot-scope="scope">
            <span>{{ moneyFormat(scope.row.beginningPaidInAmount, 'w') }}</span>
          </template>
        </el-table-column>
        <el-table-column :label="$t('期初实缴比例(%)')" align="center" prop="beginningPaidInRatio" />
      </el-table>
    </el-dialog>

    <!-- 添加或修改管理费阶段对话框 -->
    <el-dialog :title="$t('管理费设置')" :visible.sync="rateOpen" :close-on-click-modal="false" :lock-scroll="false" custom-class="dialogForm" append-to-body>
      <fundManagementPhaseForm ref="fundManagementPhaseForm" @setInvestRate="setInvestRate" />
    </el-dialog>
  </div>
</template>

<script>
import {
  saveFundManagementFee,
  getFundManagementFee,
  computeManagementFeeInfo,
  getBeginningPaidInAmountInfo,
  getFundPhaseList, getAmountByFundIdAndTime
} from '@/api/fund/managementfee/fundManagementFee'
import { getFundInvestorListByFundId, getInitFundPhaseList } from '@/api/fund/managementfee/fundManagementPhase'
    import fundManagementPhaseForm from '@/views/fund/managementfee/fundManagementPhaseForm'
import { downLoadFileOpen } from '@/utils/zipdownload'
import { delFundManageFeeDetail } from '@/api/fund/manageFeeDetail/fundManageFeeDetail'
import { ruoyiFloat } from '@/utils/ruoyi'
import { getToken } from '@/utils/auth'
import { excelTemplateCompute, getTemplateFileId } from '@/api/system/model/template/modelTemplate'
import { getFundBase, getFundName } from '@/api/fund/fundBase'
import { getCapitalCalTypeByFundId } from '@/api/fund/managementfee/rate/fundManagementRateMain'

    export default {
      components: {
        fundManagementPhaseForm
      },
        data() {
            return {
                // 计提周期字典
                accrualPeriodOptions: [], // 表单参数
                form: {
                  fundManagementPhaseList: []
                },
              // 期初投资金额出资人信息
                beginningPaidInAmountLpInfoList: [],
                // 遮罩层
                loading: false,
                rateOpen: false,
                // 基金ID
                fundId: this.$route.query.id,
                // 阶段字典
                fundPhaseOptions: [],
                // 当前基金出资人列表
                investorList: [],
                // 计提基数字典
                accrualBaseOptions: [],
                // 计提参照日类型
                accrualConsultDateOptions: [],
              // 期初实缴金额出资人信息遮罩层
              lpInfoLoading: false,
              // 是否展示期初实缴金额出资人信息
              lpInfoOpen: false,
              excelLoading: false,
              // 管理费明细计算模板ID
              managerExcelFileId: undefined,
              // 基金名称
              fundName: undefined,
              templateForm: {
                templateType: 'JJGLF',
                busId: this.$route.query.id
              },
              foundationDateDisable: false,
              // 已投项目金额
              investedProjectAmount: undefined,
              // 项目回款本金金额
              projectReturnAmount: undefined,
              // 投资期在投本金计算方式
              tzCapitalCalType: undefined,
              // 退出期在投本金计算方式
              tcCapitalCalType: undefined,
              // 延长期在投本金计算方式
              ycCapitalCalType: undefined,
              // 天数计算方式
              dayCalModeOptions: [],
              // 分配计算规则Excel 上传模板
              upload: {
                // 是否显示弹出层（项目导入）
                open: false,
                // 弹出层标题（项目导入）
                title: '',
                // 是否禁用上传
                isUploading: false,
                // 设置上传的请求头部
                headers: { Authorization: 'Bearer ' + getToken(), fundId: this.$route.query.id },
                // 上传的地址
                url: process.env.VUE_APP_BASE_API + '/model/modelTemplate/updateTemplate',
                // 遮罩层
                loading: false
              },
              // 类型
              typeOptions: [],
                // 表单校验
                rules: {
                  year: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ],
                  dayCalMode: [
                    { required: true, message: this.$t('必填信息'), trigger: ['change', 'blur'] }
                  ],
                  provisionStartDate: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ],
                  accrualConsultDate: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ],
                  provisionEndDate: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], accrualPeriod: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], yearDays: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' },
                    { pattern: /^[0-9]*$/, message: '请输入数字类型' }
                  ], beginningPaidInAmount: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], collectionDate: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ], type: [
                    { required: true, message: this.$t('必填信息'), trigger: 'blur' }
                  ] }
            }
        },
        created() {
            this.getDicts('accrual_period_type').then(response => {
                this.accrualPeriodOptions = response.data
            })
            this.getDicts('fund_phase').then(response => {
              this.fundPhaseOptions = response.data
            })
            this.getDicts('accrual_base').then(response => {
              this.accrualBaseOptions = response.data
            })
            getFundName(this.$route.query.id).then(response => {
              this.fundName = response
            })
            this.getDicts('day_cal_mode').then(response => {
              this.dayCalModeOptions = response.data
            })
            this.initInvestorList(this.$route.query.id)
          // 现金流类型
          this.getDicts('fund_expense_type').then(response => {
            this.typeOptions = response.data
          })
          // 计提参照日类型
          this.getDicts('accrual_consult_date_type').then(response => {
            this.accrualConsultDateOptions = response.data
          })
          // 获取Excel计算规则附件模板ID
          getTemplateFileId('JJGLF', this.$route.query.id).then(response => {
            this.managerExcelFileId = response.data
          })
          this.getCapitalCalType()
        },
        methods: {
            // 初始化数据
            init(data) {
              this.loading = true
                if (data != null && data.id !== undefined) {
                    getFundManagementFee(data.id).then(response => {
                      this.form = response.data
                      this.getAmount(this.form.provisionStartDate)
                      this.getCapitalCalType()
                      this.loading = false
                    })
                } else {
                  this.reset()
                  this.initFundPhaseList()
                  this.getCapitalCalType()
                  this.loading = false
                }
            },
            // 获取期限列表
            initFundPhaseList() {
              const params = {
                fundId: this.fundId
              }
              // 计算基金管理费信息
              getInitFundPhaseList(params).then(response => {
                this.form.fundManagementPhaseList = response.rows
              })
            },
            // 计算基金管理费
            calManagementFee() {
                var fee = 0
                this.form.fundManageFeeDetailList.forEach(item => {
                  fee = fee + parseFloat(item.managementFee)
                })
                this.form.receivableManagementFee = fee
            },
            // 计算再投金额
            calZtAmount() {
                var amount = 0
                this.form.fundManageFeeDetailList.forEach(item => {
                  amount = amount + parseFloat(item.beginningReinvestedAmount)
                })
              this.form.beginningReinvestedAmount = amount
            },
            // 计算实缴金额
            calSjAmount() {
                var amount = 0
                this.form.fundManageFeeDetailList.forEach(item => {
                  amount = amount + parseFloat(item.beginningPaidInAmount)
                })
              this.form.beginningPaidInAmount = amount
            },
            // 计算认缴金额
            calRjAmount() {
                var amount = 0
                this.form.fundManageFeeDetailList.forEach(item => {
                  amount = amount + parseFloat(item.subscribedAmount)
                })
              this.form.subscribedAmount = amount
            },
            copyPaste(e, scope, key) {
              e.preventDefault()
              e.stopPropagation()

              var index = scope.$index
              var fields = ['beginningPaidInAmount', 'subscribedAmount', 'beginningReinvestedAmount', 'managementFee']
              var clipData = e.clipboardData.getData('text')
              var rows = clipData.split('\r\n')
              var arr = []

              for (let i = 0; i < rows.length; i++) {
                if (rows[i]) {
                  var columns = rows[i].split('\t')
                  arr.push(columns)
                }
              }

              var currentIndex = fields.findIndex(item => item === key)
              var fieldsIndex = []

              if (currentIndex || currentIndex === 0) {
                fieldsIndex = fields.splice(currentIndex, fields.length)
              }

              if (arr.length === 1) {
                // 一行
                arr[0].forEach((column, i) => {
                  fieldsIndex.forEach((j, n) => {
                    if (column && i === n) {
                      this.form.fundManageFeeDetailList[index][j] = isNaN(column) ? '' : column
                    }
                  })
                })
              } else if (arr.length > 1) {
                var rowsArr = []
                arr.forEach(data => {
                  var obj = {}
                  data.forEach((cData, i) => {
                    fieldsIndex.forEach((j, n) => {
                      if (cData && i === n) {
                        obj[j] = isNaN(cData) ? '' : cData
                      }
                    })
                  })
                  rowsArr.push(obj)
                })

                rowsArr.forEach((item, idx) => {
                  for (const key in item) {
                    this.form.fundManageFeeDetailList[index + idx][key] = item[key]
                  }
                })
              }
              this.$forceUpdate()
            },
            // 获取基金成立日
            getFoundationDate(foundationDate) {
                if (foundationDate === 'JJCLR') {
                  getFundBase(this.$route.query.id).then(response => {
                    this.form.foundationDate = response.data.foundationDate
                    this.foundationDateDisable = true
                  })
                } else {
                  this.form.foundationDate = undefined
                  this.foundationDateDisable = false
                }
            },
            // 设置管理费费率数据
            setManagementRate(row) {
              this.rateOpen = true
              this.$nextTick(() => {
                // 调用form页面的 init 方法初始化数据
                this.$refs.fundManagementPhaseForm.init(row)
              })
            },
            setInvestRate(data) {
              console.log('维护后数据返回主表单数据', data)
              this.form.fundManagementPhaseList.forEach(item => {
                if (item.phase === data.phase) {
                  item.managementRate = data.managementRate
                  item.whetherFixed = data.whetherFixed
                  item.fundManagementPhaseInvestorList = data.fundManagementPhaseInvestorList
                }
              })
              console.log('维护后数据返回主表单数据list', this.form.fundManagementPhaseList)
            },
            // 下载系统默认基金分配计算模板
            downLoadDefaultTemplate() {
              this.downLoadExcel('/managerTemplate/fundManagerTemplate/download')
            },
          // init出资人费率列表
          initInvestorList(fundId) {
            getFundInvestorListByFundId(fundId).then(response => {
              this.investorList = response.data
            })
          },
          // 获取基金的费率中再投本金计算方式
          getCapitalCalType() {
            // 根据基金ID获取费率各阶段中再投本金计算方式
            getCapitalCalTypeByFundId(this.fundId).then(response => {
              // 投资期在投本金计算方式
              this.tzCapitalCalType = response.data.tzCapitalCalType
              // 退出期在投本金计算方式
              this.tcCapitalCalType = response.data.tcCapitalCalType
              // 延长期在投本金计算方式
              this.ycCapitalCalType = response.data.ycCapitalCalType
            })
          },
            /** 数据集配置-excel模板计算 */
            templateExcelHandle() {
              this.$refs['form'].validate(valid => {
                if (valid) {
                  this.excelLoading = true
                  var flag = true
                  for (let i = 0; i < this.form.fundManagementPhaseList.length; i++) {
                    var item = this.form.fundManagementPhaseList[i]
                    if (item.whetherFixed === null || item.whetherFixed === undefined || item.whetherFixed === '') {
                      flag = false
                      break
                    } else if (item.whetherFixed === 'Y') {
                      if (item.managementRate === null || item.managementRate === undefined || item.managementRate === '') {
                        flag = false
                        break
                      }
                    }
                  }
                  console.log('flag', flag)
                  if (flag) {
                    // 封装参与计算基金管理费带入的参数
                    const paramMap = {
                      year: this.form.year,
                      busName: this.fundName,
                      accrualPeriod: undefined,
                      dayCalMode: undefined,
                      type: undefined,
                      accrualConsultDate: undefined,
                      provisionStartDate: this.form.provisionStartDate,
                      provisionEndDate: this.form.provisionEndDate,
                      collectionDate: this.form.collectionDate,
                      yearDays: this.form.yearDays,
                      foundationDate: this.form.foundationDate,
                      // 投资期计提基数
                      tzAccrualBase: undefined,
                      // 退出期计提基数
                      tcAccrualBase: undefined,
                      // 延长期计提基数
                      ycAccrualBase: undefined,
                      // 投资期开始时间
                      tzStartDate: undefined,
                      // 投资期结束时间
                      tzEndDate: undefined,
                      // 退出期开始时间
                      tcStartDate: undefined,
                      // 退出期结束时间
                      tcEndDate: undefined,
                      // 延长期开始时间
                      ycStartDate: undefined,
                      // 延长期结束时间
                      ycEndDate: undefined,
                      // 已投项目金额
                      investedProjectAmount: this.investedProjectAmount,
                      // 项目回款本金金额
                      projectReturnAmount: this.projectReturnAmount,
                      // 投资期在投本金计算方式
                      tzCapitalCalType: this.tzCapitalCalType ? this.tzCapitalCalType : '',
                      // 退出期在投本金计算方式
                      tcCapitalCalType: this.tcCapitalCalType ? this.tcCapitalCalType : '',
                      // 延长期在投本金计算方式
                      ycCapitalCalType: this.ycCapitalCalType ? this.ycCapitalCalType : '',
                      // 投资期出资人费率列表
                      tzFundManagementPhaseInvestor: [],
                      // 退出期出资人费率列表
                      tcFundManagementPhaseInvestor: [],
                      // 延长期出资人费率列表
                      ycFundManagementPhaseInvestor: []
                    }
                    // 解析 计提周期  字典Label
                    this.accrualPeriodOptions.forEach(v => {
                      if (v.dictValue === this.form.accrualPeriod) {
                        paramMap.accrualPeriod = v.dictLabel
                      }
                    })
                    // 解析 计提参照日  字典Label
                    this.accrualConsultDateOptions.forEach(v => {
                      if (v.dictValue === this.form.accrualConsultDate) {
                        paramMap.accrualConsultDate = v.dictLabel
                      }
                    })
                    // 解析 天数计算方式  字典Label
                    this.dayCalModeOptions.forEach(v => {
                      if (v.dictValue === this.form.dayCalMode) {
                        paramMap.dayCalMode = v.dictLabel
                      }
                    })
                    // 解析 类型 字典Label
                    this.typeOptions.forEach(v => {
                      if (v.dictValue === this.form.type) {
                        paramMap.type = v.dictLabel
                      }
                    })
                    // 参数 基金期限列表 fundPhaseList
                    this.form.fundManagementPhaseList.forEach(item => {
                      if (item.phase === 'TZ') {
                        paramMap.tzStartDate = item.startDate // 起始日期
                        paramMap.tzEndDate = item.endDate // 结束日期
                        // 设置投资期管理费计提规则计提参数的数据字典label
                        this.accrualBaseOptions.forEach(accrual => {
                          if (accrual.dictValue === item.accrualBase) {
                            paramMap.tzAccrualBase = accrual.dictLabel
                          }
                        })
                        if (item.whetherFixed === 'N') {
                          item.fundManagementPhaseInvestorList.forEach(d => {
                            const investData = {
                              investorName: d.investorName, // 出资人名称
                              managementRate: parseFloat(d.managementRate) / 100 // 费率
                            }
                            // 投资期出资人费率列表
                            paramMap.tzFundManagementPhaseInvestor.push(investData)
                          })
                        } else if (item.whetherFixed === 'Y') {
                          this.investorList.forEach(d => {
                            const investData = {
                              investorName: d.investorName, // 出资人名称
                              managementRate: item.managementRate / 100 // 费率
                            }
                            // 投资期出资人费率列表
                            paramMap.tzFundManagementPhaseInvestor.push(investData)
                          })
                        }
                      } else if (item.phase === 'TC') {
                        paramMap.tcStartDate = item.startDate // 起始日期
                        paramMap.tcEndDate = item.endDate // 结束日期
                        // 设置退出期管理费计提规则计提参数的数据字典label
                        this.accrualBaseOptions.forEach(accrual => {
                          if (accrual.dictValue === item.accrualBase) {
                            paramMap.tcAccrualBase = accrual.dictLabel
                          }
                        })
                        if (item.whetherFixed === 'N') {
                          item.fundManagementPhaseInvestorList.forEach(d => {
                            const investData = {
                              investorName: d.investorName, // 出资人名称
                              managementRate: parseFloat(d.managementRate) / 100 // 费率
                            }
                            // 退出期出资人费率列表
                            paramMap.tcFundManagementPhaseInvestor.push(investData)
                          })
                        } else if (item.whetherFixed === 'Y') {
                          this.investorList.forEach(d => {
                            const investData = {
                              investorName: d.investorName, // 出资人名称
                              managementRate: item.managementRate / 100 // 费率
                            }
                            // 退出期出资人费率列表
                            paramMap.tcFundManagementPhaseInvestor.push(investData)
                          })
                        }
                      } else if (item.phase === 'YC') {
                        paramMap.ycStartDate = item.startDate // 起始日期
                        paramMap.ycEndDate = item.endDate // 结束日期
                        // 设置延长期管理费计提规则计提参数的数据字典label
                        this.accrualBaseOptions.forEach(accrual => {
                          if (accrual.dictValue === item.accrualBase) {
                            paramMap.ycAccrualBase = accrual.dictLabel
                          }
                        })
                        if (item.whetherFixed === 'N') {
                          item.fundManagementPhaseInvestorList.forEach(d => {
                            const investData = {
                              investorName: d.investorName, // 出资人名称
                              managementRate: parseFloat(d.managementRate) / 100 // 费率
                            }
                            // 延长期出资人费率列表
                            paramMap.ycFundManagementPhaseInvestor.push(investData)
                          })
                        } else if (item.whetherFixed === 'Y') {
                          this.investorList.forEach(d => {
                            const investData = {
                              investorName: d.investorName, // 出资人名称
                              managementRate: item.managementRate / 100 // 费率
                            }
                            // 延长期出资人费率列表
                            paramMap.ycFundManagementPhaseInvestor.push(investData)
                          })
                        }
                      }
                    })
                    const data = {
                      templateType: 'JJGLF',
                      busId: this.$route.query.id,
                      paramsMap: paramMap
                    }
                    excelTemplateCompute(data).then(response => {
                      this.form.excelFileId = response.datas.excelFileId
                      this.form.fundManageFeeDetailList = response.data
                      // 计算管理费金额
                      var rjAmount = 0
                      var sjAmount = 0
                      var ztAmount = 0
                      var glfAmount = 0
                      this.form.fundManageFeeDetailList.forEach(item => {
                        // 期初实缴
                        rjAmount = rjAmount + this.formatMoney(item.beginningPaidInAmount)
                        // 期初认缴
                        sjAmount = sjAmount + this.formatMoney(item.subscribedAmount)
                        // 期初在投
                        ztAmount = ztAmount + this.formatMoney(item.beginningReinvestedAmount)
                        // 管理费
                        glfAmount = glfAmount + this.formatMoney(item.managementFee)
                      })
                      this.form.beginningPaidInAmount = rjAmount
                      this.form.subscribedAmount = sjAmount
                      this.form.beginningReinvestedAmount = ztAmount
                      this.form.receivableManagementFee = glfAmount
                      this.excelLoading = false
                    })
                  } else {
                    this.msgError('请先维护管理费计提规则列表中的的费率')
                    this.excelLoading = false
                  }
                } else {
                  this.locationError(document)
                }
              })
            },
            // 下载计算的结果
            downloadCalResult(fileId) {
              downLoadFileOpen(fileId)
            },
            // 删除管理费明细
            delRowDeal(index, row) {
              const id = row.id
              if (id !== undefined && id !== '' && id != null) {
                this.$confirm(this.$t('是否确认删除?'), this.$t('警告'), {
                  confirmButtonText: this.$t('确定'),
                  cancelButtonText: this.$t('取消'),
                  type: 'warning'
                })
                  .then(function() {
                    return delFundManageFeeDetail(id)
                  }).then(() => {
                  this.form.fundManageFeeDetailList.splice(index, 1)
                  this.calManagementFee()
                  this.calZtAmount()
                  this.calSjAmount()
                  this.calRjAmount()
                  return this.msgSuccess(this.$t('删除成功'))
                })
                  .catch(function() {
                  })
              } else {
                this.form.fundManageFeeDetailList.splice(index, 1)
              }
            },
            // 表单重置
            reset() {
                this.form = {
                id: undefined,
                fundId: this.fundId,
                year: undefined,
                accrualPeriod: undefined,
                dayCalMode: undefined,
                accrualConsultDate: undefined,
                yearDays: 365,
                beginningPaidInAmount: 0,
                subscribedAmount: 0,
                beginningReinvestedAmount: 0,
                investPeriod: undefined,
                provisionStartDate: undefined,
                receivableManagementFee: 0,
                provisionEndDate: undefined,
                excelFileId: undefined,
                exitPeriod: undefined,
                extensionPeriod: undefined,
                remark: undefined,
                createBy: undefined,
                createTime: undefined,
                updateBy: undefined,
                updateTime: undefined,
                delFlag: undefined,
                fundManagementPhaseList: [],
                  type: 'SJ'
                }
                this.resetForm('form')
            },
            // 取消按钮
            cancel() {
                this.$parent.$parent.formOpen = false
                this.$parent.$parent.reset()
            },
            // 关闭form页面
            closeForm() {
                // 关闭form页面遮罩层
                this.loading = false
                // 关闭form页面
                this.$parent.$parent.formOpen = false
                // 刷新list页面
                this.$parent.$parent.getList()
            },
            /** 提交按钮 */
            submitForm: function() {
                this.$refs['form'].validate(valid => {
                    if (valid) {
                        this.loading = true
                        saveFundManagementFee(this.form).then(response => {
                            if (response.code === 200) {
                                this.msgSuccess(this.$t('保存成功'))
                                this.closeForm()
                            } else {
                                this.msgError(response.msg)
                            }
                            this.loading = false
                        })
                    } else {
                      this.locationError(document)
                    }
                })
           },
          // 阶段字典翻译
          fundPhaseFormat(row) {
            return this.selectDictLabel(this.fundPhaseOptions, row.phase)
          },
          // 计提基数字典翻译
          accrualBaseFormat(row) {
            return this.selectDictLabel(this.accrualBaseOptions, row.accrualBase)
          },
          // 选择年度和计提周期时触发
          changeHandle() {
              // 是否不为空
              if (this.form.year && this.form.accrualPeriod) {
                const params = {
                  fundId: this.fundId,
                  year: this.form.year,
                  accrualPeriod: this.form.accrualPeriod
                }
                this.loading = true
                // 计算基金管理费信息
                computeManagementFeeInfo(params).then(response => {
                  this.form.beginningPaidInAmount = response.data.beginningPaidInAmount
                  this.form.receivableManagementFee = response.data.receivableManagementFee
                  this.form.extensionPeriod = response.data.extensionPeriod
                  this.form.exitPeriod = response.data.exitPeriod
                  this.form.investPeriod = response.data.investPeriod
                  this.form.beginningReinvestedAmount = response.data.beginningReinvestedAmount
                  this.form.subscribedAmount = response.data.subscribedAmount
                  this.form.year = params.year
                  this.form.fundId = this.fundId
                  this.form.accrualPeriod = params.accrualPeriod
                  this.changeCalMode()
                })
              }
          },
          // 获取期限列表
          changeCalMode() {
            if (this.form.year && this.form.accrualPeriod && this.form.dayCalMode) {
              const params = {
                fundId: this.fundId,
                year: this.form.year,
                dayCalMode: this.form.dayCalMode,
                accrualPeriod: this.form.accrualPeriod
              }
              // this.loading = true
              // 计算基金管理费信息
              getFundPhaseList(params).then(response => {
                this.form.fundManagementPhaseList.forEach(item => {
                  response.data.forEach(d => {
                    if (item.phase === d.phase) {
                      item.days = d.days
                      item.months = d.months
                    }
                  })
                })
                // this.loading = false
              })
            } else {
              this.loading = false
            }
          },
          formatMoney(val) {
            if (val && val !== '' && !isNaN(parseFloat(val))) {
              return ruoyiFloat().formatNum(val)
            }
            return 0
          },
          // 根据年度和计提周期设置计提开始时间和结束日期
          setStartEndDate() {
            var year = this.form.year
            var accrualPeriod = this.form.accrualPeriod
            if ((year !== null && year !== undefined && year !== '') && (accrualPeriod !== null && accrualPeriod !== undefined && accrualPeriod !== '')) {
              console.log('year', this.form.year)
              if (accrualPeriod === 'YEAR') {
               this.form.provisionStartDate = year + '-01-01'
               this.form.provisionEndDate = year + '-12-31'
              } else if (accrualPeriod === 'FIRST') {
                this.form.provisionStartDate = year + '-01-01'
                this.form.provisionEndDate = year + '-03-31'
              } else if (accrualPeriod === 'SECOND') {
                this.form.provisionStartDate = year + '-04-01'
                this.form.provisionEndDate = year + '-06-30'
              } else if (accrualPeriod === 'THIRD') {
                this.form.provisionStartDate = year + '-07-01'
                this.form.provisionEndDate = year + '-09-30'
              } else if (accrualPeriod === 'FOUR') {
                this.form.provisionStartDate = year + '-10-01'
                this.form.provisionEndDate = year + '-12-31'
              }
            }
            this.getAmount(this.form.provisionStartDate)
            this.changeCalMode()
          },
          // 根据计提开始时间获取已投项目金额、项目回款本金金额
          getAmount(provisionStartDate) {
            const params = {
              fundId: this.fundId,
              provisionStartDate: provisionStartDate
            }
            // 根据基金ID和计提开始时间获取已投项目金额、项目回款本金金额
            getAmountByFundIdAndTime(params).then(response => {
              // 已投项目金额
              this.investedProjectAmount = response.data.investedProjectAmount
              // 项目回款本金金额
              this.projectReturnAmount = response.data.projectReturnAmount
            })
          },
          beginningPaidInAmountHandle() {
            if (this.form.year && this.form.accrualPeriod && this.form.beginningPaidInAmount) {
              const params = {
                fundId: this.fundId,
                year: this.form.year,
                accrualPeriod: this.form.accrualPeriod
              }
              this.lpInfoLoading = true
              this.lpInfoOpen = true
              getBeginningPaidInAmountInfo(params).then(response => {
                this.beginningPaidInAmountLpInfoList = response.data
                this.lpInfoLoading = false
              })
            }
          },
          beginningReinvestedAmountHandle() {
            if (this.form.year && this.form.accrualPeriod && this.form.beginningReinvestedAmount) {
              const params = {
                fundId: this.fundId,
                year: this.form.year,
                accrualPeriod: this.form.accrualPeriod
              }
              this.lpInfoLoading = true
              this.lpInfoOpen = true
              getBeginningPaidInAmountInfo(params).then(response => {
                this.beginningPaidInAmountLpInfoList = response.data
                this.lpInfoLoading = false
              })
            }
          },
          // (Excel规则计算分配数据)
          handleBeforeUploadExcel(file, fileList) {
            console.log(fileList)
            // .xlsx.xls格式文件
            var flag = false
            const availableSuffixes = '.xlsx.xls'
            const suffix = file.name.substr(file.name.lastIndexOf('.') + 1, file.name.length)
            if (!availableSuffixes.includes(suffix)) {
              flag = true
            }
            if (flag) {
              this.msgError(this.$t('仅支持导入 xlsx、xls格式文件！'))
              this.$refs.upload.clearFiles()
              return false
            }
          },
          // 文件上传成功处理(Excel规则计算分配数据)
          handleFileSuccessExcel(response) {
            this.upload.open = false
            this.upload.isUploading = false
            this.$refs.upload.clearFiles()
            if (response.code === 200) {
              console.log(response.data, 'response.data')
              this.managerExcelFileId = response.data.id
              this.msgSuccess(this.$t('模板更新成功！'))
            } else if (response.code === 500) {
              this.msgError(this.$t('数据异常'))
            } else {
              this.$notify({
                title: this.$t(response.msg),
                message: '',
                type: 'success'
              })
            }
          },
          // 文件达到上限处理(Excel规则计算分配数据)
          handleFileExceedExcel() {
            this.msgError(this.$t('可上传文件数量已达到上限'))
          }

        }

    }
</script>

<style lang="scss" scoped>
/deep/.uploadExcel {
  margin-left: 15px;
  display: inline-block !important;
  .el-upload-list {
    display: none;
  }
}
</style>
